var cityMove = {    // 城市行动路径
    '1' : [4,7,9],
    '2' : [5,7,8],
    '3' : [6,8,9],    
    '4' : [1,7,9,10],
    '5' : [2,7,8,10],
    '6' : [3,8,9,10], 
    '7' : [1,2,4,5,10],
    '8' : [2,3,5,6,10],
    '9' : [1,3,4,6,10],   
    '10': [4,5,6,7,8,9], 
};

var mainCities = [1,2,3];

var starLevelMax = {
    '2' : 9,
    '3' : 3,
}

var dayTime = 86400;

function LeagueWar() {
    this.leaguewars = {};       // 军团战开始后各个星级军团的详细分布
    this.isEnd = false;         // 是否计算上一轮军团战结果
    this.users = {};            // 玩家信息 uid : {score: kill: energy:level:id:city:reward:league:}
    this.leagues = {};          // 军团信息 name:{level:id:score:main_city:}
    this.registers = [];        // 已经报名一星战场的军团名字
    this.round = 0;
    this.leagueKing = {};       // 王者军团军团长和服军团长领取奖励信息{leagueName :{uid:1}}
    
    this.leagueWarStartTime = 0;    // 本次军团战开始的时间
    this.leagueWarPeriodTime = 0;   // 军团战周期

    this.starLevel = {          // 下一轮军团战参战军团的星级分布
        '1' : [],
        '2' : [],
        '3' : [],
    };

    this.preStarLevel = {       // 下一轮军团战参战军团预览分布
        '1' : [],
        '2' : [],
        '3' : [],
    };
    this.preNewLeagues = [];    // 新达到标准参战的新军团数据
    this.preStarLevelUpdate = 0;//下一轮军团战参战军团预览分布上次更新世界

    this.haveEndResult = 0;     // 是否计算好军团战结果
    this.cityMembers = {        // 城市成员
        '1' : {},
        '2' : {},
        '3' : {},
        /*
            level : {id : {city : {uid : info}}};
        */
    };

    this.cityScoreUpdates = {   // 占城积分更新时间
        '1' : {},
        '2' : {},
        '3' : {},
    };

    this.leagueRanks = {};          // 全服军团排名
    this.personRanks = {};          // 全服个人排名
    this.currentPersonRanks = {};   // 当前战场实时个人排名
    this.leaguePromotions = {};     // 上次军团战的晋升情况{'leagueName': -1/0/1}
    this.topOnes = {};              // 上次军团战每个星级和战场生成的猛将{level:{id:[uid]}}
    this.levelTopOnes = {};         // 上次军团战每个星级的猛将{level:[uid]}
    
    this.messages = {               // 消息{level:{id:[message]}} 
        '1' : {},                   // message :连斩 [name,kill]or 破连斩 [atkName,defName,kill]
        '2' : {},
        '3' : {},
    };             

    this.leagueTotalScore = {};     // 军团实时总积分{leagueName: score}

    this.updates = {};
}

LeagueWar.create = function() {
    var initLeagueWar = {
        /*
        'level' : {                     // 战场等级
            id : {                      // 战场编号
                city :{                 // 城市编号  [1-10]
                    time:''             // 占领时间
                    league:''           // 占领该城市的军团名字
                },
            }
        },
        */
    };

    var initUsers = {
        /*
        uid : {
            // headpic
            // name
            score:0     // 积分
            kill:0      // 连续斩获(大于等于3)
            energy:0    // 现在拥有的体力（有上限）
            reward:0    // 是否领取奖励

            level:      // 战场等级
            id:         // 当前战场
            city:       // 当前城
        }
        */
    };

    var initLeagues = {
        /*
        name:{          // 军团名字
            level:
            id:
            score:
            main_city:
        } 
        */ 
    };

    var initRegisters = [
        /* leagueName */ 
    ];

    var leagueWar = {
        _id: 'league_war', 
        league_war: initLeagueWar, 
        round:0,
        user:initUsers, 
        league:initLeagues,
        register:initRegisters,
        league_king:{},
    };

    gDBWorld.insert(leagueWar, function(err, result){});
};

LeagueWar.prototype = {
    init : function(callback) {
        // 读取军团战的数据
        gDBWorld.findOne({_id : 'league_war'}, {}, function(err, doc){
            if( doc ) {
                this.leaguewars = doc.league_war;
                this.round = doc.round;
                this.users = doc.user;
                this.leagues = doc.league;
                this.registers = doc.register || [];
                this.leagueKing = doc.league_king ? doc.league_king : {}; 
                this._init();
                callback && callback(true);
            }else{
                callback && callback(false);
            }
        }.bind(this));
    },

    _init : function() {
        // 计算军团战的周期
        this.leagueWarPeriodTime = gConfGlobal.LeagueWarContinueTime + gConfGlobal.LeagueWarRestTime; 
        var curRound = this.getWarRound();
        this.leagueWarStartTime = gConfGlobalServer.FirstLeagueWarTime + (curRound - 1) * this.leagueWarPeriodTime;
        // 读取数据库后,初始化cityMembers 
        var now = common.getTime();
        for( var name in this.leagues ) {
            var league = this.leagues[name];
            var level = league.level;
            var id = league.id;
            var cities = {}; 
            for( var i=1; i<=10; i++ ) {
                cities[i] = {};
            }
            this.cityMembers[level][id] = cities;
            this.cityScoreUpdates[level][id] = 0;
        }

        for( var uid in this.users ) {
            var userData = this.users[uid];
            if( !userData.league ) {
                userData.league = '';
            }

            if( userData.energy == 0 && mainCities.indexOf(userData.city) < 0 ){
                userData.energy = 700;
                this.addUpdate(util.format('user.%d', uid), userData);
            }
            var level = userData.level; 
            var id = userData.id;
            if( !this.cityMembers[level] || !this.cityMembers[level][id] || !this.cityMembers[level][id][userData.city] ) {
                delete this.users[uid];
                continue;
            }
            this.cityMembers[level][id][userData.city][uid] = userData; 
        }
        
        for( var level in this.leaguewars ) {
            for( var id in this.leaguewars[level][id] ) {
                for( var city in this.leaguewars[level][id] ) {
                    var cityData = this.leaguewars[level][id][city];
                    if( cityData.time ) {
                        continue; 
                    } 

                    cityData.time = now;
                } 
            } 
        }

        this.save();
    },
    
    addUpdate : function(key, value) {
        this.updates[key] = value;
    },

    save : function(force, callback) {
        if( !force && Object.keys(this.updates).length <= 10 ) {
            callback && callback(true);
            return;
        }
        
        var updates = this.updates;
        this.updates = {};

        gDBWorld.update({_id : 'league_war'}, {$set:updates}, function(err, result){
            if( err ) {
                ERROR(util.format('SAVE LEAGUE_WAR: %j %j', updates, err));
                callback && callback(false);
            }else {
                LOG(util.format('SAVE LEAGUE_WAR: %j', updates));
                callback && callback(true);
            }
        });
    },

    prepareWar : function() {
        var currentRound = this.getWarRound();
        if( currentRound == this.round ) return;
        
        this.endWar();

        this.isEnd = false;
        this.leagueRanks = {};          
        this.personRanks = {};          
        this.currentPersonRanks = {};   
        this.leaguePromotions = {};     
        this.topOnes={};                
        this.levelTopOnes={}; 
        this.preStarLevelUpdate = 0;
        this.preStarLevel = {
            '1' : [],
            '2' : [],
            '3' : [],
        };
        this.leagueTotalScore = {};

        this.messages = {               
            '1' : {},                   
            '2' : {},
            '3' : {},
        }; 

        this.cityMembers = {        
            '1' : {},
            '2' : {},
            '3' : {},
        };

        this.cityScoreUpdates = {   
            '1' : {},
            '2' : {},
            '3' : {},
        };

        this.leaguewars = {   
            '1' : {},
            '2' : {},
            '3' : {},
        };


        this.leagues = {}; 
        this.users = {};
        this.registers = [];
        this.leagueKing = {};
        var starLevel = this.starLevel; 
        // 删除重复的军团名字
        var leagueNameMap = {};
        for( var i = 3; i >=1; i-- ) {
            var leagues = this.starLevel[i];
            for(var j = 0, len = leagues.length; j < len; j++ ) {
                var league= leagues[j];
                if( !(league in leagueNameMap) ) {
                    leagueNameMap[league] = i;
                    continue;
                }

                leagues.splice(j, 1);
            }
        }

        var now = common.getTime();
        // 按星级分配战场id 
        for( var level in starLevel ) {
            this.leaguewars[level] = {};
            var leagueArr = starLevel[level];
            this.cityMembers[level] = {};
            for( var id = 1, len = leagueArr.length; id <= Math.ceil(len/3); id++ ) {
                this.leaguewars[level][id] = {};
                this.cityMembers[level][id] = {};
                for( var city = 1; city <= 10; city++ ) {
                    this.cityMembers[level][id][city] = {};
                    this.leaguewars[level][id][city] = {
                        'league' : '',       
                        'time':now,
                    };
                }    
                 
                for( var mainCity = 1; mainCity <= 3; mainCity++ ) {
                    if( leagueArr.length < 1 ) {
                        break;
                    }

                    var leagueName = common.randArray(leagueArr);
                    this.leaguewars[level][id][mainCity].league = leagueName; 
                    this.leagues[leagueName] = { 
                        'level':level,
                        'id':id,
                        'score':0,
                        'main_city':mainCity,
                    };
            
                    leagueArr.remove(leagueName);
                }
            }
        }

        this.round = currentRound;
        this.leagueWarStartTime = gConfGlobalServer.FirstLeagueWarTime + (this.round - 1) * this.leagueWarPeriodTime;

        this.updates = {};
        gDBWorld.update({_id:'league_war'}, {$set:{league_war:this.leaguewars, round:this.round, 
                        user:this.users, league:this.leagues, register:this.registers, league_king:this.leagueKing}},function(err, result){});
    },

    genLastWarLeague : function() {
        //  获取上次战争后的军团的星级分布情况 
        //  第一次军团战开始前
        if( 0 == this.round ) {
            this.starLevel[1] = this.registers;
            return; 
        } 
        
        var starLevelRanks = {};
        for( var i = 1; i<=3; i++ ) {
           starLevelRanks[i] =  {
               '1':[], // 排名第一军团
               '2':[], // 排名第二军团
               '3':[], // 排名第三军团
           }; 
        }

        for( var level in this.leaguewars ) {
            var levelFields = this.leaguewars[level];
            var starLevelRank = starLevelRanks[level]; 
            
            for( var id in levelFields ) {
                var warField = levelFields[id]; 
                var warFieldRanks = [];
                for( var mainCity = 1; mainCity <= 3; mainCity++) {
                    var leagueName = warField[mainCity].league;
                    if( !leagueName ) {
                        continue; 
                    }

                    warFieldRanks.push(leagueName);
                }
                
                // 对每个战场的军团积分从大到小排序
                warFieldRanks.sort(function(a, b) { 
                    return this.leagueTotalScore[b] - this.leagueTotalScore[a];
                }.bind(this));

                for( var i=0,len = warFieldRanks.length; i < len; i++) {
                    starLevelRank[i+1].push(warFieldRanks[i]); 
                }
            }

            // 对每个星级的战场积分第一名军团从大到小排序
            starLevelRank[1].sort(function(a, b) { 
                return this.leagueTotalScore[b] - this.leagueTotalScore[a];
            }.bind(this));
        }

        // 下一轮军团战参战军团的星级分布
        this.starLevel = {          
            '1' : [],
            '2' : [],
            '3' : [],
        };

        for( var leagueName in this.leagues ) {
            this.leaguePromotions[leagueName] = 0; 
        }

        // 处理保级 
        for( var i=1; i<=3; i++ ) {
            this.starLevel[i] = starLevelRanks[i][2];
        }
        this.starLevel[1] = this.starLevel[1].concat(starLevelRanks[1][3]);
        this.starLevel[3] = this.starLevel[3].concat(starLevelRanks[3][1]);
        
        // 处理降级
        for( var i = 3; i >= 2; i-- ) {
            var starLevelRank3 = starLevelRanks[i][3];
            this.starLevel[i-1] = this.starLevel[i-1].concat(starLevelRank3); 
            for( var k = 0, len = starLevelRank3.length; k < len; k++ ) {
                this.leaguePromotions[starLevelRank3[k]] = -1;
            }
        }

        // 处理升级
        for( var i = 2; i >= 1; i-- ) {
            var promoteNum = starLevelMax[i+1] - this.starLevel[i+1].length; 
            var starLevelRank1 = starLevelRanks[i][1].slice(0, promoteNum);

            // 升级
            this.starLevel[i+1] = this.starLevel[i+1].concat(starLevelRank1);  

            for( var k = 0, len = starLevelRank1.length; k < len; k++ ) {
                this.leaguePromotions[starLevelRank1[k]] = 1;
            }
            
            // 超过限制,保级
            var starLevelRank1Left = starLevelRanks[i][1].slice(promoteNum);
            this.starLevel[i] = this.starLevel[i].concat(starLevelRank1Left);
        }

        // 处理军团按星级排行榜升降级数据
        for( var level in this.leagueRanks ) {
            var leagueRank = this.leagueRanks[level];
            for( var i=0,max=leagueRank.length; i<max; i++ ) {
                var data = leagueRank[i];
                data.promotion = this.leaguePromotions[data.league];
            }
        }

        this.starLevel[1] = this.registers.slice();
        // 删除重复的军团名字
        var leagueNameMap = {};
        for( var i = 3; i >=1; i-- ) {
            var leagues = this.starLevel[i];
            for(var j = 0, len = leagues.length; j < len; j++ ) {
                var league= leagues[j];
                if( !(league in leagueNameMap) ) {
                    leagueNameMap[league] = i;
                    continue;
                }

                leagues.splice(j, 1);
            }
        }
    },
    
    isUnderWar : function() {
        var now  = common.getTime(); 
        if( now < gConfGlobalServer.FirstLeagueWarTime) {
            return false;
        }

        var leagueWarTime = (now - gConfGlobalServer.FirstLeagueWarTime) % this.leagueWarPeriodTime; 
        if( leagueWarTime <= gConfGlobal.LeagueWarContinueTime ) {
            return true;    
        } 
        
        return false;
    },

    getWarRound : function() {
        var now = common.getTime();
        var curRound = Math.ceil((now - gConfGlobalServer.FirstLeagueWarTime) / this.leagueWarPeriodTime);
        if( curRound < 0 ) {
            curRound = 0;
        }   
        
        return curRound;
    },  

    genLeagueRank : function() {
        this.leagueRanks = {};
        for( var name in this.leagues ) {
            var leagueData = this.leagues[name];
            var leagueObj = gLeague.leagues[name];

            var level = leagueData.level;
            var id = leagueData.id;

            var totalScore = this.updateLeagueTotalScore(name);

            var leagueRank = this.leagueRanks[level];
            if( !leagueRank ) {
                leagueRank = [];
                this.leagueRanks[level] = leagueRank;    
            }

            var data = {
                'league': name,
                'level': leagueObj.level,
                'num' : Object.keys(leagueObj.members).length,
                'score' : totalScore,
            //    'promotion' : this.leaguePromotions[name],
            };

            leagueRank.push(data);
        }

        for( var level in this.leaguewars ) {
            var leagueRank = this.leagueRanks[level];
            if( !leagueRank ) {
                this.leagueRanks[level] = [];
            }else{
                leagueRank.sort(function(a, b){return b.score - a.score;});
            }
        }
    },

    genPersonRank : function() {
        this.personRanks = {};
        for( var level in this.cityMembers ) {
            var leaguewar = this.cityMembers[level];
            var personRank = [];
            for( var id in leaguewar ) {
                var cities = leaguewar[id];
                for( var cityId in cities ) {
                    var users  = cities[cityId];
                    for( var uid in users ) {
                        var userData = users[uid];  
                        var leagueName = this.leaguewars[userData.level][userData.id][userData.city].league;
                        if( !this.leagues[leagueName] ) continue;
                        var user = {
                            'uid' : +uid,
                            'name': gUserInfo.getUser(uid).name,
                            'league': leagueName,
                            'kill':userData.kill,
                            'score':userData.score + this.leagues[leagueName].score,
                        }

                        personRank.push(user);
                    }
                }
            }

            personRank.sort(function(a, b){return b.score - a.score});
            personRank = personRank.slice(0, 16);
            this.personRanks[level] = personRank;
        }
    },

    genTopOnes : function() {
        for( var level in this.leaguewars ) {
            this.topOnes[level] = {};
            this.levelTopOnes[level] = [];
            for( var id in this.leaguewars[level] ) {
                var topOne = [];
                this.topOnes[level][id] = topOne; 
                var leagues = this.genBattleFieldLeagueRank(level, id);
                // 第一名军团的个人积分前2名为猛将         
                var rankDatas = this.getPersonRankOfLeague(leagues[0].name, level, id);
                if( 0 == rankDatas.length ) {
                    continue; 
                }

                if( rankDatas[0] ) {
                    topOne.push(rankDatas[0].uid);
                    this.levelTopOnes[level].push(rankDatas[0].uid);
                }
                
                if( rankDatas[1] ) {
                    topOne.push(+rankDatas[1].uid);
                    this.levelTopOnes[level].push(rankDatas[1].uid);
                }
                 
                // 第二名军团的个人积分第1名为猛将
                if( !leagues[1] ) {
                    continue;
                } 

                rankDatas = this.getPersonRankOfLeague(leagues[1].name, level, id);
                if( rankDatas[0] ) {
                    topOne.push(rankDatas[0].uid);
                    this.levelTopOnes[level].push(rankDatas[0].uid);
                }
            } 
        }
    },

    getPersonRankOfLeague : function(leagueName, level, id) {
        // 获取每个军团内的个人排行
        var personRank = [];
        var cities = this.cityMembers[level][id];
        for( var id in cities ) {
            var city = cities[id]; 
            for( var uid in city ) {
                var userData = city[uid];
                if( this.leaguewars[userData.level][userData.id][userData.city].league != leagueName ) {
                    continue; 
                } 

                var rank = {
                    'uid': +uid,
                    'score': userData.score + this.leagues[leagueName].score, 
                }

                personRank.push(rank);
            }
        }

        personRank.sort(function(a, b){return b.score - a.score;});

        return personRank.slice(0,2);
    },

    getCurrentPersonRank : function(level, id) {
        var now = common.getTime();

        if( !(level in this.currentPersonRanks) ) {
            this.currentPersonRanks[level] = {};
        }

        if( !(id in this.currentPersonRanks[level]) ) {
            this.currentPersonRanks[level][id] = {'rank':[], 'last_update':0};
        }

        var oldRank = this.currentPersonRanks[level][id];
        if( (now - oldRank.last_update) > 60 ) {
            var personRank = [];
            var cities = this.cityMembers[level][id];
            for( var id in cities ) {
                var city = cities[id]; 
                for( var uid in city ) {
                    var userData = city[uid];
                    var leagueName = this.leaguewars[userData.level][userData.id][userData.city].league; 
                    if( !this.leagues[leagueName] ) continue;
                    var rank = {
                        'uid': +uid,
                        'name': gUserInfo.getUser(uid).name, 
                        'score': userData.score + this.leagues[leagueName].score, 
                        'kill': userData.kill, 
                        'league': leagueName, 
                    }

                    personRank.push(rank);
                }
            }

            personRank.sort(function(a, b){return b.score - a.score;});
            personRank = personRank.slice(0, 22);

            oldRank.rank = personRank;
            oldRank.last_update = now;
        }

        return oldRank.rank;
    },

    genBattleFieldLeagueRank : function(level, id) {
        // 每个战场的军团排序
        var leagues = [];
        var cities = gLeagueWar.leaguewars[level][id];
        for( var i=1; i<=3; i++ ) {
            var league = cities[i].league;
            if( !league ) continue;
            var leagueData = gLeague.leagues[league];
            leagues.push({
                'name':league, 
                'score':gLeagueWar.leagueTotalScore[league] || 0,
                'level': leagueData ? leagueData.level : 2,
                'num': leagueData ? Object.keys(leagueData.members).length : 30,
                'promotion': this.leaguePromotions[league] || 0,
            });
        }

        leagues.sort(function(a, b) { return b.score - a.score; } );

        return leagues;
    },

    getWarResult : function(level, id, uid){
        // 该战场军团信息,自己排名
        
        var rank = 100;
        var rankDatas = this.getCurrentPersonRank(level, id);
        for( var i=1; i<=rankDatas.length; i++ ) {
            if( rankDatas[i-1].uid == uid ) {
                rank = i;
                break;
            }
        }
        var userData = this.getUser(uid);
        var user = {
            'rank': rank, 
            'name': gUserInfo.getUser(uid).name, 
            'score': userData.score
        };

        // 军团排序
        var leagues = this.genBattleFieldLeagueRank(userData.level, userData.id);
        var tops = [];
        var topOnes = this.topOnes[level][id] ? this.topOnes[level][id] : [];
        for( var i =0, len = topOnes.length; i<len; i++ ) {
            var topUid = +topOnes[i];       
            var top = {
                'uid' : topUid,   
                'name': gUserInfo.getUser(topUid).name,
            }

            tops.push(top);
        }
        
        return {'user':user, 'leagues':leagues, 'top': tops};
    },

    updateLeagueScore : function(level, id){
        // 更新城池占领积分
        var now = common.getTime();
        if( (now - this.cityScoreUpdates[level][id]) < 60 ) {
            return; 
        }

        var cities = this.leaguewars[level][id];
        var addScores = {};
        for( var city in cities ) {

            var cityData = cities[city];
            var cityOccupied = this.cityOccupied(level, id, city);
            if( !cityOccupied ) continue;

            if( !cityData.time ) {
                cityData.time = now; 
            }

            var timePassed = now - cityData.time;

            var score = Math.floor(timePassed/3600*gConfLeagueWarCity[city].ScorePerHour);

            cityData.time = common.getTime();
            this.addUpdate(util.format('league_war.%d.%d.%d', level, id, city), cityData);

            if( !(cityOccupied in addScores) ) {
                addScores[cityOccupied] = score;
            }else{
                addScores[cityOccupied] += score;
            }
        }

        for( var league in addScores ) {
            this.leagues[league].score += addScores[league];
            this.addUpdate(util.format('league.%s', league), this.leagues[league]);
            this.updateLeagueTotalScore(league);
        }

        this.cityScoreUpdates[level][id] = now;
    },

    updateLeagueTotalScore : function(name) {
        var leagueData = this.leagues[name];
        var leagueObj = gLeague.leagues[name];

        var leagueMemberNum = 0;
        var totalScore = 0;
        for ( var uid in leagueObj.members ) {
            var userData = this.getUser(+uid);
            if( !userData ) continue;

            leagueMemberNum += 1; 
            totalScore += userData.score;
        }

        totalScore += leagueData.score * leagueMemberNum;
        this.leagueTotalScore[name] = totalScore;
        return totalScore;
    },

    getUser : function(uid) {
        return this.users[uid];
    },

    addUser : function(uid, leagueName, gradeLevel) {
        if( uid in this.users ) return;
        
        var leagueData = this.leagues[leagueName]; 
        var level = leagueData.level;
        var id = leagueData.id;
        var city = leagueData.main_city;

        var user = {
            'score': gConfGlobal.LeagueWarBaseScore, 
            'kill': 0,
            'energy': gConfGradeLevel[gradeLevel].EnergyLimit,
            'city': city,
            'level': level,
            'id': id,
            'reward' : 0,
            'league' : leagueName,
        };

        this.users[uid] = user;
        this.addUpdate('user.'+uid, user);
        this.cityMembers[level][id][city][uid] = user;

        return user;
    },

    move : function(uid, toCity) {
        var leaveEmpty = false;  // 返回离开后是否空城

        var userData = this.getUser(uid);
        var level = userData.level;
        var id = userData.id;
        var fromCity = userData.city;

        if( fromCity == toCity ) return;
        
        var fromCityOccupied = this.cityOccupied(level, id, fromCity);
        var warField = this.cityMembers[level][id];
        delete warField[fromCity][uid];

        var cities = this.leaguewars[level][id];

        // 离开后,检查空城,计算积分
        var cityOccupied = this.cityOccupied(level, id, fromCity);
        if( mainCities.indexOf(fromCity) < 0 && !cityOccupied && fromCityOccupied) {
            var cityData = cities[fromCity];

            var now = common.getTime();
            var timePassed = now - cityData.time;
            var score = Math.floor(timePassed/3600*gConfLeagueWarCity[fromCity].ScorePerHour);
            this.leagues[fromCityOccupied].score += score;

            this.addUpdate(util.format('league.%s', fromCityOccupied), this.leagues[fromCityOccupied]);
            this.updateLeagueTotalScore(fromCityOccupied);

            cityData.league = '';
            cityData.time = common.getTime();
            this.addUpdate(util.format('league_war.%d.%d.%d', level, id, fromCity), cityData);
        }

        // 进入空城
        cityOccupied = this.cityOccupied(level, id, toCity);
        if( mainCities.indexOf(toCity) < 0 && !cityOccupied ) {
            var cityData = cities[toCity];
            cityData.league = userData.league ? userData.league : gLeague.getUserLeague(uid).name;
            cityData.time = common.getTime();

            this.addUpdate(util.format('league_war.%d.%d.%d', level, id, toCity), cityData);
        }
        
        warField[toCity][uid] = userData;

        userData.city = toCity;
        this.addUpdate(util.format('user.%d', uid), userData);
    },

    cityOccupied : function(level, id, city) {
        var cityLeague = "";
        if( mainCities.indexOf(city) >= 0 ) {
            // 如果city 为主城
            cityLeague = this.leaguewars[level][id][city].name;
        }else {
            var members = this.cityMembers[level][id][city];
            var memberUids = Object.keys(members);
            if( memberUids.length > 0 ) {
                var uid = memberUids[0];
                var userLeagueName = this.getUser(uid).league;
                cityLeague = userLeagueName ? userLeagueName : gLeague.getUserLeague(uid).name;
            }
            
            var cityData = this.leaguewars[level][id][city];

            if( mainCities.indexOf(city) >= 0 ) {
                cityData.league = cityLeague;
            }

        }

        return cityLeague;
    },

    backHome : function(uid) {
        var userData = this.getUser(uid);
        var cityData = this.leaguewars[userData.level][userData.id][userData.city];
        
        var userLeagueName = this.getUser(uid).league;
        userLeagueName = userLeagueName ? userLeagueName : gLeague.getUserLeague(uid).name;
        var mainCity = this.leagues[userLeagueName].main_city;
        if( userData.city == mainCity ) return;

        return this.move(uid, mainCity);
    },

    endWar : function() {
        if( this.isEnd ) return;

        this.genPersonRank();
        this.genLeagueRank();
        this.genLastWarLeague();

        this.genTopOnes();
        this.isEnd = true;
    },

    haveReward : function(uid) {
        if( this.isUnderWar() ) return false;
        var userData = gLeagueWar.getUser(uid);
        if( !userData ) return false;
        return !userData.reward;
    },

    addMessage : function(level, id, message) {
        var messages = this.messages[level][id];
        if( !messages ) {
            messages =[];
            this.messages[level][id] = messages;
        }

        if( messages.length >= 3 ) {
            messages.shift(); 
        }

        messages.push(message);
    },

    getMessage : function(level, id) {
        var messages = this.messages[level][id];
        if( !messages ) {
            messages =[];
            this.messages[level][id] = messages;
        }

        return messages;
    },
    
    getPreviewWar : function() {
        var now = common.getTime();
        if( (now - this.preStarLevelUpdate) < 3 ) {
           return this.preStarLevel;
        }

        this.preStarLevel = {       // 下一轮军团战参战军团预览分布
            '1' : [],
            '2' : [],
            '3' : [],
        };

        this.starLevel[1] = this.registers.slice();

        var starLevel = this.starLevel; 
        for( var level in starLevel ) {
            var leagueNames = starLevel[level];
            for( var i = 0, len = leagueNames.length; i < len; i++ ) {
                var leagueName = leagueNames[i]; 
                var leagueObj = gLeague.leagues[leagueName];
                this.preStarLevel[level].push({
                    'league' : leagueName, 
                    'level': leagueObj.level, 
                    'num': Object.keys(leagueObj.members).length,
                    'name' : gUserInfo.getUser(leagueObj.leader).name,
                });
            }
        }

        this.preStarLevelUpdate = now;
        return this.preStarLevel;
    },

    isRegistered : function( leagueName ) {
        var registered = false;
        if( this.isUnderWar() ) {
            if( (this.registers.indexOf(leagueName) >= 0) 
                || (leagueName in this.leagues) ) {
                registered = true; 
            } 

        }else {
            this.endWar();
            if( (this.registers.indexOf(leagueName) >= 0) 
                || (this.starLevel[2].indexOf(leagueName)>=0)
                || (this.starLevel[3].indexOf(leagueName)>=0) ) {
                registered = true; 
            } 
        }

        return registered;
    },
}

exports.get = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 3; resp.desc = 'not in league'; break;
        }

        var leagueName = league.name;
        var gradeLevel = req.args.grade_level;

        if( Object.keys(league.members).length < gConfGlobal.LeagueWarPlayerNumMin ) {
            resp.code = 1; resp.desc = 'not enough members'; break;
        }

        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 3; resp.desc = 'not under war'; break;
        }

        // 分配战场
        gLeagueWar.prepareWar();
        
        // 是否成功进入军团战
        if( !(leagueName in gLeagueWar.leagues) ) {
            resp.code = 0; resp.data.started = 1; break;
        }
        
        // 进入战场
        var userData = gLeagueWar.getUser(uid);
        if( !userData ) {
            userData = gLeagueWar.addUser(uid, leagueName, gradeLevel);
            resp.data.enter = 1;
        }

        if( !userData.league ) {
            userData.league = leagueName; 
        }

        // 有机会更新战场军团占城积分
        gLeagueWar.updateLeagueScore(userData.level, userData.id);
        
        var cities = gLeagueWar.leaguewars[userData.level][userData.id];
        var leagues = [];
        for( var i=1; i<=3; i++ ) {
            var league = cities[i].league;
            if( !league ) continue;
            leagues.push({'name':league, 'score':gLeagueWar.leagueTotalScore[league] || 0});
        }


        resp.data.cities = cities;
        resp.data.leagues = leagues;
        resp.data.user = userData;
        resp.data.league_score = gLeagueWar.leagues[leagueName].score; 
        resp.data.message = gLeagueWar.getMessage(userData.level, userData.id);

        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.get_city = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'not under war'; break;
        }

        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 3; resp.desc = 'not in league'; break;
        }
        
        if( isNaN(req.args.city) || !(req.args.city in cityMove) ) {
            resp.code = 1; resp.desc = 'invalid args'; break;
        }

        var city = parseInt(req.args.city);

        var userData = gLeagueWar.getUser(uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        var members = gLeagueWar.cityMembers[userData.level][userData.id][city];
        if( !members ) {
            resp.code = 1; resp.desc = 'invalid city'; break;
        }

        var memberNames = {};
        for( var member in members ) {
            var memberInfo = gUserInfo.getUser(member);
            memberNames[member] = memberInfo.name;
        }
        
        resp.data.members = members;
        resp.data.member_names = memberNames;
        resp.data.city = gLeagueWar.leaguewars[userData.level][userData.id][city];
    }while(false);

    onHandled();
}

exports.get_energy = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 3; resp.desc = 'not in league'; break;
        }

        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'not under war'; break;
        }

        var userData = gLeagueWar.getUser(req.uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        if( mainCities.indexOf(userData.city) < 0 ) {
            resp.code = 1; resp.desc = 'not in main city'; break;
        }
        
        var maxEnergy = gConfGradeLevel[req.args.grade_level].EnergyLimit;
        if( userData.energy >= maxEnergy ) {
            resp.code = 1; resp.desc = 'full'; break;
        }

        var energyGot = maxEnergy - userData.energy;
        if( energyGot > req.args.energy ) {
            energyGot = req.args.energy;
        }

        userData.energy += energyGot;
        gLeagueWar.addUpdate(util.format('user.%d', req.uid), userData);

        resp.data.energy_got = energyGot;

        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.fight = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 3; resp.desc = 'not in league'; break;
        }

        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'not under war'; break;
        }

        var gradeLevel = req.args.grade_level;

        if( isNaN(req.args.enemy) ) {
            resp.code = 1; resp.desc = 'invalid args'; break;
        }

        var enemy = parseInt(req.args.enemy);
        var enemyData = gLeagueWar.getUser(enemy);
        if( !enemyData ) {
            resp.code = 1; resp.desc = 'enemy not in war'; break;
        }

        var userData = gLeagueWar.getUser(uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        if( userData.energy <= 0 || enemyData.energy <= 0 ) {
            resp.code = 3; resp.desc = 'not enough energy'; break;
        }
        
        // 不是同伙
        if( enemyData.level != userData.level || enemyData.id != userData.id ) {
            resp.code = 1; resp.desc = 'not in same battle field'; break;
        }
        
        var level = userData.level;
        var id = userData.id;
        var cities = gLeagueWar.leaguewars[level][id];
        var enemyCityData = cities[enemyData.city];
        var userCityData = cities[userData.city];
        var enemyCity = enemyData.city;

        if( enemyCityData.league == userCityData.league ) {
            resp.code = 3; resp.desc = 'not enemy'; break;
        }

        // 进攻路径
        if( cityMove[userData.city].indexOf(enemyData.city) < 0 ) {
            resp.code = 3; resp.desc = 'invalid path'; break;
        }
        
        var isAddAttack = 0;
        var addToWhich = '';
        if( mainCities.indexOf(userData.city) >= 0 ) {
            isAddAttack = 1; 
            addToWhich = 'attack';
        }else if( mainCities.indexOf(enemyData.city) >= 0 ) {
            isAddAttack = 1; 
            addToWhich = 'defence';
        }

        fightLeagueWar(uid, enemy, isAddAttack, addToWhich, function(battleReport) {
            if( !battleReport ) {
                resp.code = 1; resp.desc = 'pvp error';
                onHandled();
                return;
            }
            
            var userCostEnergy = 0;
            var enemyCostEnergy = 0;

            var userName = gUserInfo.getUser(uid).name;
            var enemyName = gUserInfo.getUser(enemy).name; 
            var succ = battleReport.success;
            if( succ ) {
                enemyCostEnergy = gConfGlobal.LeagueWarFailEnergy;
                var healthPercent = battleReport.atk_remain_health/battleReport.atk_team_health;
                userCostEnergy = Math.min(Math.floor(Math.max(10, 50*(1 - healthPercent))), 40);
                    
                var oldEnemyKill = enemyData.kill;
                userData.kill += 1;
                enemyData.kill = 0;
                userData.score += gConfGlobal.LeagueWarWinScore;
                enemyData.score += gConfGlobal.LeagueWarFailScore;

                if( level >= gConfGradeLevel[gradeLevel].BattleLevel ) {
                    resp.data.grade_xp = Math.floor(gConfGlobal.LeagueWarGradeBaseXp * (1+userData.kill*0.02));
                }
                
                if( userData.kill >= 3) {
                    gLeagueWar.addMessage(level,id,[userName, userData.kill]);
                }
                
                if( oldEnemyKill >= 3) {
                    gLeagueWar.addMessage(level,id,[userName, enemyName, oldEnemyKill]);
                }

            }else{
                userCostEnergy = gConfGlobal.LeagueWarFailEnergy;
                var healthPercent = battleReport.def_remain_health/battleReport.def_team_health;
                enemyCostEnergy = Math.min(Math.floor(Math.max(10, 50*(1 - healthPercent))), 40);

                userData.kill = 0;
                userData.score += gConfGlobal.LeagueWarFailScore;
                enemyData.score += gConfGlobal.LeagueWarWinScore;
            }
            
            // 给对手添加消息 
            var message = {
                'uid': uid,
                'type' : 'league_war',
                'name' : userName, 
                'time' : common.getTime(), 
                'succ' : succ, 
                'energy': enemyCostEnergy,
                'score': succ ? gConfGlobal.LeagueWarFailScore : gConfGlobal.LeagueWarWinScore,
                'replay' : gReplay.addReplay(battleReport),
            };
            gMessage.addMessage(enemy, message); 

            if( enemyCostEnergy > enemyData.energy ) {
                enemyCostEnergy = enemyData.energy;
            }

            if( userCostEnergy > userData.energy ) {
                userCostEnergy = userData.energy;
            }

            enemyData.energy -= enemyCostEnergy;
            userData.energy -= userCostEnergy;
            
            var canOccupy = true;
            // 没体力需要回城
            if( userData.energy <= 0 ) {
                gLeagueWar.backHome(uid);
                canOccupy = false;
            }
            if( enemyData.energy <= 0 ) {
                // 打跑对面所有人,并且自己没回主城,占领
                gLeagueWar.backHome(enemy);
            }else{
                canOccupy = false;
            }

            if( canOccupy && mainCities.indexOf(enemyCity) < 0 ) {
                var cityOccupied = gLeagueWar.cityOccupied(level, id, enemyCity);
                if( !cityOccupied ) {
                    gLeagueWar.move(uid, enemyCity);
                }
            }
            
            gLeagueWar.addUpdate(util.format('user.%d', uid), userData);
            gLeagueWar.addUpdate(util.format('user.%d', enemy), enemyData);

            resp.data.battle = battleReport;
            resp.data.energy = -userCostEnergy;

            gLeagueWar.save();
            onHandled();
        });
        return;
    }while(false);

    onHandled();
}

exports.move = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 3; resp.desc = 'not in league'; break;
        }

        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'not under war'; break;
        }

        if( isNaN(req.args.city) ) {
            resp.code = 1; resp.desc = 'invalid args'; break;
        }

        var city = parseInt(req.args.city);
        var userData = gLeagueWar.getUser(uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        if( userData.energy <= 0 ) {
            resp.code = 3; resp.desc = 'no energy'; break;
        }

        if( userData.city == city ) {
            resp.code = 1; resp.desc = 'move self'; break;
        }
        
        if( !gLeagueWar.leaguewars[userData.level][userData.id][city] ) {
            resp.code = 1; resp.desc = 'invalid city'; break;
        }

        // 不能进入别人的主城,只能回自己
        var userLeagueName = userData.league ? userData.league : gLeague.getUserLeague(uid).name;
        if( mainCities.indexOf(city) >= 0 && gLeagueWar.leagues[userLeagueName].main_city != city ) {
            resp.code = 1; resp.desc = 'other team main city'; break;
        }
        
        var cityOccupied = gLeagueWar.cityOccupied(userData.level, userData.id, city);
        // 不是自己军团占领的城
        if( cityOccupied && (cityOccupied != userLeagueName) ) {
            resp.code = 3; resp.desc = 'occupying by other'; break;
        }

        if( cityMove[userData.city].indexOf(city) < 0 ) {
            resp.code = 1; resp.desc = 'invalid city move'; break;
        }

        gLeagueWar.move(uid, city);
        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.rank_global = function(req, resp, onHandled) {
    do {
        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }

        gLeagueWar.endWar();

        resp.data.personal_rank = gLeagueWar.personRanks;
        resp.data.league_rank = gLeagueWar.leagueRanks;
        resp.data.topones = gLeagueWar.levelTopOnes;

        gLeagueWar.save();
    }while(false);
    onHandled();
}

exports.rank_personal = function(req, resp, onHandled) {
    do {
        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'not under war'; break;
        }

        var userData = gLeagueWar.getUser(req.uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        var rank = gLeagueWar.getCurrentPersonRank(userData.level, userData.id);
        resp.data.rank = rank;
    }while(false);

    onHandled();
}

exports.end_war = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 3; resp.desc = 'not in league'; break;
        }

        var userData = gLeagueWar.getUser(req.uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }

        gLeagueWar.endWar();
         
        var leagueName = gLeagueWar.leaguewars[userData.level][userData.id][userData.city].league;
        if( !leagueName ) {
            leagueName = gLeague.users[req.uid];
            userData.city = gLeagueWar.leagues[leagueName].main_city;
            gLeagueWar.addUpdate(util.format('user.%d', req.uid), userData);
        }

        var result = gLeagueWar.getWarResult(userData.level, userData.id, req.uid);

        var leagues = gLeagueWar.genBattleFieldLeagueRank(userData.level, userData.id); 
        var leagueRank = 0;
        for( var i=0, len = leagues.length; i<len; i++) {
            if( leagues[i].name == leagueName ) {
                leagueRank = i+1;
                break; 
            } 
        }

        var leagueWarRankConf = gConfLeagueWarRank[leagueRank]; 
        if( !leagueWarRankConf ) {
            resp.code = 1; resp.desc = 'no league rank'; break;
        }

        var leagueStarLevel = gLeagueWar.leagues[leagueName].level;
        var isPromotion = false;
        for( var i = 0, len = result.leagues.length; i < len; i++ ) {
            var resultLeague = result.leagues[i];
            if( resultLeague.promotion && (resultLeague.name == leagueName) ) {
                isPromotion = true;break;
            }
        }       

        var isLeaderGroup = gLeague.isLeaderGroup(leagueName, uid);
        // 王者军团
        var curRound = gLeagueWar.round;
        if( (1 == leagueRank) && (1 == curRound)
            && isPromotion && ( 1 == leagueStarLevel ) ) {
            resp.data.league_king = curRound + 1;
        }else if( (1 == leagueRank) && ( 2 == curRound)
            && isPromotion && ( 2 == leagueStarLevel ) ) {
            resp.data.league_king = curRound + 1; 
        }
        
        if( resp.data.league_king && isLeaderGroup ) {
            if( !(leagueName in gLeagueWar.leagueKing) ) gLeagueWar.leagueKing[leagueName] = {};
            var leagueKing = gLeagueWar.leagueKing;
            if( Object.keys(leagueKing[leagueName]).length < 3 )  {
                leagueKing[leagueName][uid] = 1;
                gLeagueWar.addUpdate(util.format('league_king.%s', leagueName), gLeagueWar.leagueKing[leagueName]);
                resp.data.leader_group = true;
            }
        }

        resp.data.user = result.user;
        resp.data.league_score = gLeagueWar.leagues[leagueName].score;

        var userScore = userData.score + gLeagueWar.leagues[leagueName].score;
        resp.data.glory = Math.floor(3500*0.6*userScore/(0.6*userScore + 8000)) + leagueWarRankConf['Glory'+ userData.level];
        resp.data.leagues = result.leagues;
        resp.data.top = result.top;

        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.get_reward = function(req, resp, onHandled) {
    var uid = req.uid;
    do {
        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }

        var userData = gLeagueWar.getUser(uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        gLeagueWar.endWar();

        if( !gLeagueWar.haveReward(uid) ) {
            resp.code = 1; resp.desc = 'no reward'; break;
        }
       
        var leagueName = gLeagueWar.leaguewars[userData.level][userData.id][userData.city].league;
        if( !leagueName ) {
            leagueName = gLeague.users[uid];
            userData.city = gLeagueWar.leagues[leagueName].main_city;
        }

        var leagues = gLeagueWar.genBattleFieldLeagueRank(userData.level, userData.id); 
        var leagueRank = 0;
        for( var i=0, len = leagues.length; i<len; i++) {
            if( leagues[i].name == leagueName ) {
                leagueRank = i+1;
                break; 
            } 
        }

        var leagueWarRankConf = gConfLeagueWarRank[leagueRank]; 
        if( !leagueWarRankConf ) {
            resp.code = 1; resp.desc = 'no league rank'; break;
        }

        if( userData.level >= gConfGradeLevel[req.args.grade_level].BattleLevel ) {
            resp.data.grade_xp = leagueWarRankConf.GradeXp; 
        }   

        userData.reward = 1;
        gLeagueWar.addUpdate(util.format('user.%d', uid), userData);
        

        var userScore = userData.score + gLeagueWar.leagues[leagueName].score;
        resp.data.glory = Math.floor(3500*0.6*userScore/(0.6*userScore + 8000)) + leagueWarRankConf['Glory'+ userData.level];
        resp.data.topone = gLeagueWar.topOnes[userData.level][userData.id].indexOf(uid) >= 0 ? 1: 0 ;   // 是否猛将
        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.preview_war = function(req, resp, onHandled) {
    do {
        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }

        gLeagueWar.endWar();

        resp.data.field = gLeagueWar.getPreviewWar();

        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.register = function(req, resp, onHandled) {
    do {
        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }
        
        var uid = req.uid;
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 1; resp.desc = 'not in league'; break;
        }

        var leagueName = league.name;
        if( !(league.leader == uid || league.vice_leader.indexOf(uid)>=0) ) {
            resp.code = 1; resp.desc = 'not leader or vice_leader'; break;
        }

        if( Object.keys(league.members).length < gConfGlobal.LeagueWarPlayerNumMin ) {
            resp.code = 1; resp.desc = 'not enough members'; break;
        }

        gLeagueWar.endWar();
        if( gLeagueWar.isRegistered(leagueName) ) {
            break; 
        }
        
        gLeagueWar.registers.push(leagueName);
        gLeagueWar.addUpdate('register', gLeagueWar.registers);

        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.get_register = function(req, resp, onHandled) {
    do {
        var uid = req.uid;
        if( gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'under war'; break;
        }

        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 1; resp.desc = 'not in league'; break;
        }

        var leagueName = league.name;
        if( Object.keys(league.members).length < gConfGlobal.LeagueWarPlayerNumMin ) {
            resp.code = 1; resp.desc = 'not enough members'; break;
        }

        gLeagueWar.endWar();
        var registered = 0;
        if( gLeagueWar.isRegistered(leagueName) ) {
            registered = 1; 
        }
        
        resp.data.registered = registered; 

        gLeagueWar.save();
    }while(false);

    onHandled();
}

exports.get_ex_energy = function(req, resp, onHandled) {
    do {
        var uid = req.uid;
        var league = gLeague.getUserLeague(uid);
        if( !league ) {
            resp.code = 1; resp.desc = 'not in league'; break;
        }

        if( !gLeagueWar.isUnderWar() ) {
            resp.code = 1; resp.desc = 'not under war'; break;
        }

        var userData = gLeagueWar.getUser(uid);
        if( !userData ) {
            resp.code = 1; resp.desc = 'not in war'; break;
        }

        var lastGotTime = req.args.ex_energy_time;

        var now = common.getTime();
        var leagueWarStartTime = gLeagueWar.leagueWarStartTime;
        
        var day = new Date(leagueWarStartTime*1000);  
        var dayStartTime = +(new Date(day.getFullYear(), day.getMonth(), day.getDate()))/1000;
        
        // 领取体力时间
        var gotTime = dayStartTime + gConfGlobal.LeagueWarGotExEnergyHour * 3600;
        
        if( leagueWarStartTime > gotTime ) {
            resp.code = 1; resp.desc = 'error got time'; break;
        }

        if( now < gotTime ) {
            resp.code = 1; resp.desc = 'not in got time'; break;
        }
        
        // 是否已经领取
        if( lastGotTime >= gotTime ) {
            resp.code = 1; resp.desc = 'have got'; break;
        }
        
    }while(false);

    onHandled();
}

exports.LeagueWar = LeagueWar;
